<?php

namespace app\commands\queue;

use app\commands\BaseController;
use app\common\service\UploadService;
use app\common\service\weixin\TemplateService;
use app\models\member\Member;
use app\models\QueueList;
use app\modules\web\controllers\UploadController;

class ListController extends BaseController
{
    /**
     * php yii queue/list/run
     */
    public function actionRun(){
        $list = QueueList::find()->where(['stats'=>-1])->orderBy( ['id'=>SORT_ASC] )->limit(10)->all();
        if( !$list ){
            return $this->echoLog("NO DATA TO HANDLE");
        }

        foreach( $list as $_item ){
            switch( $_item['queue_name'] ){
                case "pay":
                    $this->hanlePay( $_item );
                    break;
                case "bind":
                    $this->handleBind( $_item );
                    break;
                case "member_avatar":
                    $this->handleMemberAvatar( $_item );
                    break;
            }
            $_item->status = 1;
            $_item->updated_time = date('Y-m-d H:i:s');
            $_item->update(0);
        }
    }

    private function handlePay( $item ){
        $data = @json_decode( $item['data'],true );
        if( !isset( $data['member_id']) || !isset( $data['pay_order_id'] ) ){
            return false;
        }

        if( !$data['member_id'] || !data['pay_order_id'] ){
            return false;
        }
        TemplateService::PayNotice( $data['pay_order_id'] );
    }

    /**
     * 绑定微信相关通知
     */
    private function handleBind( $item ){
        $data = @json_decode( $item['data'],true );
        if( !isset( $data['member_id']) || !isset( $data['openid'] )  ){
            return false;
        }

        if( !$data['member_id'] || !$data['openid'] ){
            return false;
        }

        $member_info = Member::findOne(['id' => $data['member_id']]);
        if( !$member_info ) {
            return false;
        }

        TemplateService::bindNotice( $data['member_id'] );
        return true;

    }

    public function handleMemberAvatar( $item )
    {
        $data = @json_decode( $item['data'],true );
        if( !isset($data['member_id']) || !isset($data['avatar_url']) ){
            return false;
        }

        if( !$data['member_id'] || !$data['avatar_url'] ){
            return false;
        }

        $member_info = Member::findOne(['id' =>$data['member_id']]);
        if( !$member_info ){
            return false;
        }

        $ret = UploadService::uploadByUrl( $data['avatar_url'],"avatar" );
        if( $ret ){
            $member_info->avatar = $ret['path'];
            $member_info->update(0);
        }
        return true;
    }
}